<?php
include "counter.php";
function locate_place($sql, $placeid) {
    global $find;
    global $find_like;
    global $place_rows;
    print "<!-- $sql -->\n";
    $placeq = mysql_query($sql);
    if ($place_rows = mysql_num_rows($placeq)) {
        $place = mysql_fetch_array($placeq);
        while ( $place['type'] == "alias" ) {
            $placeq = mysql_query("select * from places where ".
                      "f_key = '". $place['within']."'");
            $place = mysql_fetch_array($placeq);
        }
    }
    if (!$find && $place_rows > 1) {
        $find = ereg_replace(".*:", "", $placeid);
    }
    print "<!-- sql found = $place_rows rows -->\n";
    return $place;
}
if (!$columns) {
    $columns = 3;
}
$place = $counter->get_input('place', 'place', 'get');
if(!$place) {
    $place = "All";
    $myenv = substr($_SERVER['REQUEST_URI'], 1);
    if(preg_match("/". preg_quote(substr($_SERVER['SCRIPT_NAME'], 1), "/") ."/", $myenv)) {
        $myenv = preg_replace("/". preg_quote(substr($_SERVER['SCRIPT_NAME'], 1), "/")."(\/)?/", "", $myenv);
    }
    if(preg_match("/^(.+\/{1})$/", $myenv)) {
        $myenv = substr($myenv, 0, strlen($myenv)-1);
    }
    $myenv = explode("/",$myenv);
    if($counter->get_input($myenv[0], 'place')) {
        $place = $myenv[0];
    }
}
$find_like = "=";
$find = $counter->get_input('find', 'place', 'post');
if ($find) {
    $findq =  mysql_query("select * from places where name like '%$find'");
    if ( mysql_num_rows($findq) == 1 ) {
        $found = mysql_fetch_array($findq);
        while ( $found['type'] == "alias" ) {
            $findq =  mysql_query("select * from places where f_key = '".$found['within']."'");
            $found = mysql_fetch_array($findq);
        }
        $place=$found['name'];
        $find="";
    }
}
$place_hold = $place;
$placeq = "select * from places where name = '$place'";
$place_res = locate_place($placeq, $place);
if (!$place_res) {
    $place_new = ereg_replace(":.*:", ":%:", $place);
    print "<!-- $place  reurned nothing try $place_new -->\n";
    $placeq = "select * from places where name like '$place_new'";
    $place_res = locate_place($placeq, $place_new);
}
if (!$place_res) {
    list ($country, $state, $city) = split(":", $place);
    print "<!-- $place_new  reurned nothing try $country:$state -->\n";
    $placeq = "select * from places where name = '$country:$state'";
    $place_res = locate_place($placeq, "$country:$state");
}
if (!$place_res) {
    print "<!-- $country:$state  reurned nothing try %:$state:$city -->\n";
    $placeq = "select * from places where name like '%:$state:$city'";
    $place_res = locate_place($placeq, $city);
}
if (!$place_res) {
    print "<!-- %:$state:$city  reurned nothing try %:$state -->\n";
    $placeq = "select * from places where name like '%:$state'";
    $place_res = locate_place($placeq, $state);
    if ($place_res) {
        $cc = ereg_replace(":.*", "", $place_res['name']);
        $placeq = "select * from places where name = '$cc::$city'";
        $place_res = locate_place($placeq, $state);
    }
}
if (!$place_res) {
    print "<!-- %:$state:$city  reurned nothing try $country -->\n";
    $placeq = "select * from places where name = '$country'";
    $place_res = locate_place($placeq, $county);
}
if (!$place_res ) {
    if (!$find ) {
        $find = $city;
    }
    print "<!-- $County  reurned nothing Use the world -->\n";
    $placeq = "select * from places where name = 'all'";
    $place_res = locate_place($placeq, "All");
}
$place = $place_res;
function placeurl($name, $longname) {
    global $PHP_SELF;
    $placeurl = urlencode($name);
    return "<a href=\"$PHP_SELF?place=$placeurl\">$longname</a>";
}
function page_bar($personcount, $quotedname) {
    global $PHP_SELF;
    if ($personcount > 90 ) {
        $page_no = 0;
        while (($page_no * 90) < $personcount ) {
            if (!$page_no) {
                print "[ <a href=\"".$PHP_SELF."?place=$quotedname\">First</a>";
            } else if ((($page_no * 90 ) + 90) > $personcount ) {
                print " | <a href=\"$PHP_SELF?place=$quotedname&page=$page_no\">Last</a> ]";
            } else {
                print " | <a href=\"$PHP_SELF?place=$quotedname&page=".$page_no."\">Page ".($page_no + 1)."</a>";
            }
            $page_no++;
        }
    }
}
?>
<?php pagehead("Information about ".$place['longname']) ?>
<BODY bgcolor="white">
<?php pagetop() ?>
<table>
   <tr>
       <th>Seach for a place</th>
       <td><form action="<?php echo $PHP_SELF ?>" method=post>
       <input type=text name =find size=20>
       <input type=submit value="Go">
       </form>
       </td>
   </tr>
</table>
<?php
 if($find) {
     $findq =  mysql_query("select * from places where name like '%:$find' order by name");
     if ( mysql_num_rows($findq) > 1 ) {
         print "<table><tr><th align=left>Search results for $find";
         while ( $found = mysql_fetch_array($findq) ) {
             print "<tr><td>";
             place_bar ($found, 1);
         }
         print "</table>";
     } else {
         print "Search results<br>Nothing found for $find";
     }
 }
?>
<h1>Linux users in <?php echo $place['longname'] ?></h1>
<?php place_bar($place); ?>
<BR>
<img src="/gifs/Logo-small.png" alt="Linux Counter Logo">
<?php
   $lowname = strtolower($place['name']);
   if (file_exists("/home/counter/base/www/bycountry/$lowname.png")) {
       echo "<img src=\"/bycountry/$lowname.png\"><p>\n";
   }
?>
<font size=-2><a href="/legal.html">Copyright &copy; Linux Counter Project. Usage
restricted.</a></font><br>
<?php 
   /* Should be changed to preg_replace(faster) but I'll do that after I get cvs */
   $place_html = ereg_replace(".*html:", "", $place['f_clean']);
   if ($place_html != $place['f_clean'] ) {
       print "$place_html<br clear=all>";
   }
?>
<table border=0 width="80%">
   <tr>
       <td>
       <table>
          <tr>
              <th align=right>Place code:</th>
              <td><?php echo $place['name'] ?></td>
          </tr>
          <tr>
              <th align=right>Maintainer(s):</th>
              <td><?php findmaintainer($place) ?></td>
          </tr>
          <tr>
              <th align=right>Population:</th>
              <td><?php echo $place['population'] ?> million</td>
          </tr>
          <tr>
              <th align=right>Hostcount:</th>
              <td><?php echo $place['hostcount'] ?></td>
          </tr>
          <tr>
              <th align=right>Linux users:</th>
              <td><?php echo $place['users'] ?></td>
          </tr>
<?php 
if ($place['population'] > 0) {
?>
          <tr>
              <th align=right>Linux density:</th>
<?php
   printf("              <td>%5.2f users/million</td>", $place['users'] / $place['population']);
?>
          </tr>
<?php
}
if ($place['hostcount'] > 0) {
?>
          <tr>
              <th align=right>Linux users per 1000 IP hosts:</th>
<?php
   printf("              <td>%5.2f</td>", $place['users'] * 1000/ $place['hostcount']);
?>
          </tr>
<?php
}
?>
       </table>
       <p>
<?php
if ($place['type'] == "country" && $place['users'] > 0) {
    $tq = mysql_query("select * from temp_short where country = '". $place['name']."'");
    $td = mysql_fetch_array($tq);
    printf ( "%s is no. %s in the density statistics, with %s users/Mpop<br>\n", $place['longname'], $td['rank'], $td['userdensity']);
    if ($td['rank'] > 1) {
        $tq = mysql_query("select * from temp_short where rank = ". ($td['rank'] - 1));
        if ($tq == 0) {
            print("</table>MySQL error: " . mysql_errno() . ":" . mysql_error());
            die("Query for count failed");
        }
        $tdup = mysql_fetch_array($tq);
        $need = $tdup['userdensity'] * $td['population'] - $td['users'] + 1;
        printf("%s needs %d more users to pass %s and become no. %d<br>\n", $place['longname'], $need, placeurl($tdup['country'], $tdup['name']), $td['rank'] - 1);
    }
    $tq = mysql_query("select * from temp_short where rank = " . ($td['rank'] + 1));
    if (mysql_num_rows($tq) > 0) {
        $tdown = mysql_fetch_array($tq);
        $need = $td['userdensity'] * $tdown['population'] - $tdown['users'] + 1;
        printf("%s needs %d more users to pass %s and become no. %d<br>\n", placeurl($tdown['country'], $tdown['name']), $need, $td['name'], $td['rank']);
    }
}
if ($place['within'] != 0) {
    $uq = mysql_query("select * from places where f_key = " . $place['within']);
    $upper = mysql_fetch_array($uq);
    //printf("$place['longname'] is part of %s<br>\n", placeurl($upper['name'], $upper['longname']));
}
?>
       </td>
   </tr>
</table>
<!-- Subordinate places -->
<?php
function uindex ($personcount, $place, $quotedplace) {
    global $PHP_SELF;
    if ($personcount < 91) {
        return;
    }
    $alphaq = mysql_query("select substring(name, 1, 1) as c from persons where placeid = '$quotedplace' and lower(f_raw) like '%may_publish:y%' group by c");
    print "<h4>";
    while ($alpha = mysql_fetch_row($alphaq)) {
        $a = strtoupper($alpha['0']);
        if ( $a >= "A" && $a <= "Z" ) {
            print "<a href=\"$PHP_SELF?start=$a&place=". urlencode($quotedplace) ."#person\">$a</a> &nbsp; ";
        }
    }
    print "</h4><p>";
}
function presentlist($type, $title) {
    global $PHP_SELF;
    global $place;
    global $columns;
    $col = floor($columns/2);
    if ($col == 0) { $col = 1; }
    $places = mysql_query("select * from places where within = ". $place['f_key'] ." and type = '$type' and users > 0 order by longname");
    if (mysql_num_rows($places) == 0) { return; }
    print "<h2>$title within ".$place['longname']."</h2>\n";
    if (mysql_num_rows($places) > 20) {
        $alphaq = mysql_query("select substring(longname, 1, 1) as c from places where within = ". $place['f_key'] ." and type = '$type' and users > 0 group by c");
        print "<h4>";
        while ($alpha = mysql_fetch_row($alphaq)) {
            $a = strtoupper($alpha['0']);
            print "<a href=\"#place_".$type."_$a\">$a</a> &nbsp; ";
        }
        print "</h4><p>\n";
    }
?>
<table>
   <tr>
<?php
    $preva = "";
    for ($itemcount=0; $itemcount <= $col; $itemcount += 2) {
?>
       <th align=left>Name</th>
       <th>Users</th>
<?php
    }
?>
   </tr>
<?php
    $itemcount = 0;
    while ($sub = mysql_fetch_array($places)) {
        $placeurl = urlencode($sub['name']);
        $a = strtoupper(substr($sub['longname'], 0, 1));
        if ($itemcount % $col == 0) {
            print "   <tr>\n";
        }
        ++ $itemcount;
        print "       <td>";
        if ($a <> $preva) {
            print "<a name=\"place_".$type."_$a\"> </a>";
            $preva = $a;
        }
        print "<a href=\"$PHP_SELF?place=$placeurl\">".$sub['longname']."</a></td>\n";
        print "       <td align=right>".$sub['users']."</td>\n";
        print "   <tr>\n";
    }
    print "</table>\n";
}
presentlist("country", "Countries");
presentlist("state", "States/Regions");
presentlist("city", "Cities");
?>
<!-- Subordinate persons -->
<?php
   $quotedname = mysql_escape_string($place['name']);
   $totalcount = dbcount("persons", "placeid = '$quotedname'");
   $privatecount = dbcount("persons", "placeid = '$quotedname' and  lower(f_raw) not like '%may_publish:y%'");
   $personcount = dbcount("persons", "placeid = '$quotedname' and  lower(f_raw) like '%may_publish:y%'");
   if ($personcount > 90) {
       $start_after = urldecode($next);
       $page = $counter->get_input('page', 'number', 'get');
       $start = $counter->get_input('start', 'alpha', 'get');
       if ($page) {
           $start=$page*90;
           $end = $start + 90;
           if ($end > $personcount) {
               $end = $personcount;
           }
           $note = "Listing users $start to $end of $personcount registered persons.";
           $persons = mysql_query("select * from persons where placeid = '$quotedname' and lower(f_raw) like '%may_publish:y%' order by name limit $start,90");
       } elseif($start) {
           //      $note = "Listing the first 90 of $personcount registered persons.";
           $persons = mysql_query("select * from persons where placeid = '$quotedname' and name >= '$start' and lower(f_raw) like '%may_publish:y%' order by name limit 90");
       } else {
           $note = "Listing the first 90 of $personcount registered persons.";
           $persons = mysql_query("select * from persons where placeid = '$quotedname' and lower(f_raw) like '%may_publish:y%' order by name limit 90");
       }
   } else {
       $note = "Listing $personcount registered persons.";
       $persons = mysql_query("select * from persons where placeid = '$quotedname' and lower(f_raw) like '%may_publish:y%' order by name");
   }
   if (mysql_num_rows($persons) > 0) {
       print "<a name=person></a><h2>Persons within ".$place['longname']."</h2>\n";
       print $note;
       if ($privatecount > 0) {
           printf ("<br>There are %d persons who donot wish to be listed<hr>", $privatecount);
       }
       page_bar($personcount, $quotedname);
       uindex($personcount, $place, $quotedname);
       print "\n";
       if ($personcount < 20) {
           $columns = 1;
       }
       # damn Netscape....must respect margin..
?>
<p><table width="95%">
<?php
       $itemcount = 0;
       while ($sub = mysql_fetch_array($persons)) {
           if ($itemcount++ % $columns == 0) {
               if ($itemcount > 0) { print "   </tr>\n"; }
               print "   <tr>\n";
           }
           printf("       <td width=\"%d%%\">%s</td>\n", 100/$columns, person_url($sub['f_key'], $sub['name']));
           $home_page = ereg_replace(".*homepage:", "", $sub['f_raw']);
           // if ( $home_page  != $sub['f_raw'] ) {
           // 	$home_page = ereg_replace("ident:.*", "", $home_page);
           // printf ("<td width=\"%d%%\"><a href=\"$home_page\">$home_page</a>", 50/$columns);
           // } else {
           // printf ("<td width=\"%d%%\">", 50/$columns);
           // }
       }
       print "</table>";
   }
?>
<p>
<?php
page_bar($personcount, $quotedname);
pagebottom()
?>
</body>
</html>
